一、查看当前 brew 数据源

首先,你可以通过以下命令查看当前 brew 核心仓库、Homebrew Bottles(二进制包)等组件的源地址:

# 查看 brew 核心仓库的远程源地址
cd "$(brew --repo)" && git remote -v

# 查看 homebrew-core 仓库的源地址
cd "$(brew --repo homebrew/core)" && git remote -v

# 查看 homebrew-cask 仓库的源地址(用于安装桌面应用)
cd "$(brew --repo homebrew/cask)" && git remote -v

# 查看 Bottles 镜像配置(二进制包源,关键!)
echo $HOMEBREW_BOTTLE_DOMAIN

输出示例(官方源):

plaintext

origin  https://github.com/Homebrew/brew.git (fetch)
origin  https://github.com/Homebrew/brew.git (push)

二、修改 brew 数据源(切换到国内镜像)

国内常用的镜像源有中科大源清华源阿里源,这里以最稳定的清华源为例讲解。

1. 临时切换 Bottles 源(仅当前终端生效)

如果只是临时需要加速下载,无需修改仓库源,只需设置环境变量:

# 临时设置 Bottles 镜像(清华源)
export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles

2. 永久修改数据源(推荐)

步骤 1:修改 brew 核心仓库源
# 切换 brew 主仓库到清华源
git -C "$(brew --repo)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git

# 切换 homebrew-core 仓库到清华源
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git

# 切换 homebrew-cask 仓库到清华源(可选)
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git
步骤 2:永久设置 Bottles 镜像(二进制包源)

Bottles 是 brew 预编译的二进制包,修改这个源对下载速度提升最明显,需要写入 shell 配置文件:

# 针对 bash 用户(默认 shell)
echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles' >> ~/.bash_profile
source ~/.bash_profile

# 针对 zsh 用户(macOS 新版默认)
echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles' >> ~/.zshrc
source ~/.zshrc

三、恢复官方源(如需)

如果镜像源出问题,可恢复官方默认源:

# 恢复 brew 主仓库官方源
git -C "$(brew --repo)" remote set-url origin https://github.com/Homebrew/brew.git

# 恢复 homebrew-core 官方源
git -C "$(brew --repo homebrew/core)" remote set-url origin https://github.com/Homebrew/homebrew-core.git

# 恢复 homebrew-cask 官方源
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://github.com/Homebrew/homebrew-cask.git

# 清除 Bottles 镜像配置(删除 shell 配置文件中的对应行)
# 以 zsh 为例,编辑 ~/.zshrc,删除包含 HOMEBREW_BOTTLE_DOMAIN 的行,然后执行:
source ~/.zshrc

# 重置 brew 缓存(可选)
brew cleanup

四、验证修改是否生效

执行以下命令,若输出的源地址是清华镜像地址,则修改成功:

# 验证核心仓库源
cd "$(brew --repo)" && git remote -v

# 验证 Bottles 源
echo $HOMEBREW_BOTTLE_DOMAIN

总结

  1. 查看源:通过 git remote -v 查看仓库源,echo $HOMEBREW_BOTTLE_DOMAIN 查看二进制包源;
  2. 修改源:优先修改 homebrew-coreHOMEBREW_BOTTLE_DOMAIN(最影响速度),推荐使用清华 / 中科大镜像;
  3. 恢复源:通过 git remote set-url 重置仓库源,删除 shell 配置中的 Bottles 环境变量即可恢复官方源。

注意:修改源后建议执行 brew update 刷新缓存,确保新源生效。